package orm

import (
	"database/sql/driver"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type LocalTime time.Time

func (t LocalTime) MarshalJSON() ([]byte, error) {
	tTime := time.Time(t)
	b := []byte(fmt.Sprintf("\"%v\"", tTime.Format("2006-01-02 15:04:05")))
	return b, nil
}

func (t *LocalTime) UnmarshalJSON(data []byte) error {
	if string(data) == "null" {
		return nil
	}
	var err error
	ti, err := time.ParseInLocation(`"`+"2006-01-02 15:04:05"+`"`, string(data), time.Local)
	*t = LocalTime(ti)
	return err
}

func (t LocalTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	tlt := time.Time(t)
	//判断给定时间是否和默认零时间的时间戳相同
	if tlt.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return tlt, nil
}

func (t *LocalTime) Scan(v interface{}) error {
	if value, ok := v.(time.Time); ok {
		*t = LocalTime(value)
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

type Model struct {
	ID        uint           `json:"Id" form:"Id" gorm:"column:id;primaryKey;comment:主键ID"`                              // 主键ID
	CreatedAt LocalTime      `json:"createdAt"  time_format:"2006-01-02 15:04:05" gorm:"column:created_at;comment:创建时间"` // 创建时间
	UpdatedAt LocalTime      `json:"updatedAt" time_format:"2006-01-02 15:04:05" gorm:"column:updated_at;comment:更新时间"`  // 更新时间
	DeletedAt gorm.DeletedAt `json:"-" form:"-" gorm:"column:deleted_at;comment:删除时间;index"`                             // 删除时间
}
